/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * serialForm.java
 *
 * Created on Dec 16, 2011, 9:55:51 AM
 */
package readreport;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

/** How long to wait for the open to finish up. */
public class serialForm extends javax.swing.JFrame {

    public static final int TIMEOUTSECONDS = 30;
    /** The baud rate to use. */
    public static final int BAUD = 1200;
    /** A mapping from names to CommPortIdentifiers. */
    protected HashMap map = new HashMap();
    /** The name of the choice the user made. */
    /** The JComboBox for parallel ports  serialPortsChoice*/
    protected final int PAD = 5;
    private String selectedPortName;
    private CommPortIdentifier selectedPortIdentifier;
    private SerialPort serialPort;
    private String value;
    ByteArrayOutputStream baos;
    private InputStream inputStream;

    /** Creates new form serialForm */
    public serialForm() {
        initComponents();
        populate();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        serialPortsChoice = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        OkBtn = new javax.swing.JButton();
        exitBtn = new javax.swing.JButton();
        valuetbx = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);

        serialPortsChoice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        serialPortsChoice.setEnabled(false);
        serialPortsChoice.setName("serialPortsChoice"); // NOI18N

        jLabel1.setText("Serial Ports");
        jLabel1.setName("jLabel1"); // NOI18N

        OkBtn.setText("OK");
        OkBtn.setName("OkBtn"); // NOI18N
        OkBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                OkBtnMouseClicked(evt);
            }
        });

        exitBtn.setText("Exit");
        exitBtn.setName("eixitBtn"); // NOI18N
        exitBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                exitBtnMouseClicked(evt);
            }
        });

        valuetbx.setText("jTextField1");
        valuetbx.setName("valuetbx"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(OkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(valuetbx, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                            .addComponent(serialPortsChoice, 0, 158, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serialPortsChoice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(valuetbx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OkBtn)
                    .addComponent(exitBtn))
                .addGap(17, 17, 17))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void OkBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_OkBtnMouseClicked
    if (serialPortsChoice.getSelectedItem() != null) {
        try {
            selectedPortName = (String) serialPortsChoice.getSelectedItem();
            selectedPortIdentifier = (CommPortIdentifier) map.get(selectedPortName);
            switch (selectedPortIdentifier.getPortType()) {
                case CommPortIdentifier.PORT_SERIAL:
                    serialPort = (SerialPort) selectedPortIdentifier.open("BalanceComm", TIMEOUTSECONDS * 1000);
                    inputStream = serialPort.getInputStream();
                    // set up the serial port
                    serialPort.setSerialPortParams(BAUD, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_ODD);
                    serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT);
                    break;
                default:  // Neither parallel nor serial??
                    throw new IllegalStateException("Unknown port type " + selectedPortName);
            }

            serialPort.notifyOnDataAvailable(true);
            value = "";
            serialPort.addEventListener(new SerialPortEventListener() {

                public void serialEvent(SerialPortEvent ev) {
                    switch (ev.getEventType()) {
                        case SerialPortEvent.DATA_AVAILABLE:
                            BufferedReader is = new BufferedReader(new InputStreamReader(inputStream));
                            try {
                                System.out.println(is.readLine());
                                valuetbx.setText(is.readLine());
                               
                               
                            } catch (IOException ex) {
                            }
                            break;
                    }
                }
            });
            
        }   catch (IOException ex) {
                Logger.getLogger(serialForm.class.getName()).log(Level.SEVERE, null, ex);
            } catch (PortInUseException ex) {
            Logger.getLogger(serialForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedCommOperationException ex) {
            Logger.getLogger(serialForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TooManyListenersException ex) {
            Logger.getLogger(serialForm.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}//GEN-LAST:event_OkBtnMouseClicked

private void exitBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitBtnMouseClicked
    dispose();
}//GEN-LAST:event_exitBtnMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(serialForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(serialForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(serialForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(serialForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new serialForm().setVisible(true);
            }
        });
    }

//<editor-fold defaultstate="collapsed" desc="populate">
    protected void populate() {
        // get list of ports available on this particular computer,
        // by calling static method in CommPortIdentifier.
        Enumeration pList = CommPortIdentifier.getPortIdentifiers();

        // Process the list, putting serial and parallel into ComboBoxes
        while (pList.hasMoreElements()) {
            CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
            // System.out.println("Port " + cpi.getName());
            map.put(cpi.getName(), cpi);
            if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                serialPortsChoice.setEnabled(true);
                serialPortsChoice.addItem(cpi.getName());
            }
        }
        serialPortsChoice.setSelectedIndex(-1);
    }
//</editor-fold>
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton OkBtn;
    private javax.swing.JButton exitBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JComboBox serialPortsChoice;
    private javax.swing.JTextField valuetbx;
    // End of variables declaration//GEN-END:variables

    CommPortIdentifier getSelectedIdentifier() {
        return selectedPortIdentifier;
    }
}
